<template>
  <div>
    <!-- title -->
    <PageTitle>
      {{ $t("menu.M_10408090") }}
    </PageTitle>
    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      :page-size="pageSize"
      :total="totalPage"
      :current-page="pageIndex"
      @current-change="currentChangeHandle"
    >
      <div class="p-4">
        <el-form inline @submit.prevent.native>
          <el-form-item>
            <el-input
              v-model="condition"
              maxlength="64"
              :placeholder="$t('system.ram.query_condition')"
              @blur="() => (condition = condition.trim())"
              @keyup.enter.native="fetchData((pageIndex = 1))"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="w-8" @click="fetchData((pageIndex = 1))">
              <svg-icon icon-class="search" />
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              v-permission="{
                permission: '10408090.MANAGE',
              }"
              type="primary"
              class="w-8"
              @click="handleAdd()"
            >
              <svg-icon icon-class="plus" />
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="listLoading"
        :show-overflow-tooltip="true"
        :data="tableData"
        stripe
      >
        <el-table-column :label="$t('system.ram.app_name')" prop="name" min-width="250">
          <template v-slot="{ row }">
            <div style="cursor: pointer" @click="handleDetails(row)">
              {{ row.name }}
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('system.ram.app_id')" prop="username" min-width="300">
          <template v-slot="{ row }">
            <div>
              {{ row.username }}
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('common.status')" prop="status" width="100">
          <template v-slot="{ row }">
            <el-tag
              :type="row.status == 0 ? 'danger' : row.status == 1 ? 'success' : ''"
              size="small"
            >
              <span>{{ statusFilter(row.status) }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.create_time')" prop="creTime" width="200">
          <template v-slot="{ row }">
            <div :title="timeFilter(row.creTime)">
              {{ dateFilter(row.creTime) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column width="75">
          <template v-slot="scope">
            <el-dropdown
              v-if="
                verifyPermission('10408090.MANAGE') &&
                scope.row.username != loginUserName &&
                scope.row.managerFlag != 1
              "
              @command="handleClick"
            >
              <el-button text class="w-8">
                <svg-icon icon-class="MoreFilled" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="scope.row.status === 1"
                    :command="beforeHandleCommand('lock', scope.row)"
                  >
                    <svg-icon icon-class="Lock" />
                    {{ $t("user.lock") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 0"
                    :command="beforeHandleCommand('unlock', scope.row)"
                  >
                    <svg-icon icon-class="Unlock" />
                    {{ $t("user.unlock") }}
                  </el-dropdown-item>
                  <el-dropdown-item :command="beforeHandleCommand('delete', scope.row)">
                    <svg-icon icon-class="Delete" />
                    {{ $t("common.delete") }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <ram-add
      v-model="addUserVisible"
      :title="$t('system.ram.add_app')"
      @submit="fetchData"
      @postKey="showKey($event)"
    />

    <el-dialog
      v-model="keyVisible"
      :title="$t('system.ram.show_key')"
      @close="handleKeyClose"
    >
      <el-form ref="keyForm" :model="keyForm" label-position="top" @submit.prevent.native>
        <el-form-item :label="$t('system.ram.app_id')">
          <el-input v-model="keyForm.ramId" :readonly="true" />
        </el-form-item>
        <el-form-item :label="$t('system.ram.app_key')">
          <el-input v-model="keyForm.ramKey" :readonly="true" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button text @click="copyKey">{{ $t("system.ram.copy") }}</el-button>
          <el-button  type="primary" @click="handleKeyClose()">{{
            $t("common.confirm")
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { deleteUser, getUserPage, lockUser, unlockUser } from "@/api/user";
import { timeFilter, dateFilter } from "@/filters";

import { verifyBtnPermission } from "@/utils";

import RamAdd from "./components/ram-add.vue";
import PageTitle from "@/components/PageTitle/index.vue";
export default {
  components: {
    RamAdd,
    PageTitle,
  },
  data() {
    return {
      loginUserName: "",
      tableData: [],
      listLoading: false,
      selectedData: [],
      paginationShow: true,
      condition: "",
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      operationType: "",
      addUserVisible: false,
      editRoleId: "",
      addRoleVisible: false,
      keyVisible: false,
      keyForm: {
        ramId: "",
        ramKey: "",
        userId: "",
      },
    };
  },
  mounted() {
    const userInfo = JSON.parse(
      localStorage.getItem(this.$store.getters.keys.storage.username)
    );
    this.loginUserName = userInfo.username;
    this.fetchData();
  },
  methods: {
    statusFilter(status) {
      const statusMap = {
        0: "Locked",
        1: "Valid",
      };
      return statusMap[status];
    },
    timeFilter,
    dateFilter,
    showKey(res) {
      if (res) {
        this.keyForm.ramId = res.ramId;
        this.keyForm.ramKey = res.ramKey;
        this.keyForm.userId = res.userId;
        this.keyVisible = true;
      }
    },
    handleKeyClose() {
      this.keyForm.ramId = "";
      this.keyForm.ramKey = "";
      this.keyVisible = false;
      this.$router.push({
        path: `/system/ram/detail/${this.keyForm.userId}`,
      });
    },
    copyKey() {
      var textarea = document.createElement("textarea");
      textarea.value =
        "App ID:\n" + this.keyForm.ramId + "\n" + "App Key:\n" + this.keyForm.ramKey;
      // 添加input标签
      document.body.appendChild(textarea);
      // 选中input标签
      textarea.select();
      // 执行复制
      document.execCommand("copy");
      // 成功提示信息
      this.$message.success(this.$t("common.success"));
      // 移除input标签
      document.body.removeChild(textarea);
    },

    verifyPermission(val) {
      return verifyBtnPermission(val);
    },
    fetchData() {
      this.listLoading = true;
      getUserPage({
        pageNo: this.pageIndex,
        pageSize: this.pageSize,
        userType: 2,
        status: "",
        condition: this.condition,
      })
        .then((res) => {
          this.listLoading = false;
          this.tableData = res.data;
          this.totalPage = res.rows;
        })
        .catch((e) => {
          this.listLoading = false;
          this.$confirmError(e);
        });
    },
    handleDetails(row, column, e) {
      this.$router.push({
        path: `/system/ram/detail/${row.userId}`,
      });
    },
    getLogo(logo) {
      if (logo) {
        const avatars = this.$store.getters.avatars.find((v) => v.name == logo);
        if (avatars) {
          return avatars.src;
        }
      }
      return this.$store.getters.avatars[0].src;
    },
    handleLock(row) {
      this.$confirm(
        this.$t("system.ram.sure_lock") + `[${row.name}]?`,
        this.$t("common.tips"),
        {
          confirmButtonText: this.$t("common.confirm"),
          cancelButtonText: this.$t("common.cancel"),
          type: "warning",
        }
      ).then(() => {
        lockUser(row.userId)
          .then((res) => {
            this.$message({
              message: this.$t("user.lock_success"),
              type: "success",
            });
            this.fetchData();
          })
          .catch(this.$confirmError);
      });
    },
    handleUnlock(row) {
      this.$confirm(
        this.$t("system.ram.sure_unlock") + `[${row.name}]?`,
        this.$t("common.tips"),
        {
          confirmButtonText: this.$t("common.confirm"),
          cancelButtonText: this.$t("common.cancel"),
          type: "warning",
        }
      ).then(() => {
        unlockUser(row.userId)
          .then((res) => {
            this.$message({
              message: this.$t("user.unlock_success"),
              type: "success",
            });
            this.fetchData();
          })
          .catch(this.$confirmError);
      });
    },
    handleDelete(row) {
      this.$confirm(this.$t("user.delete_tip", { username: row.name }), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      }).then(() => {
        deleteUser(row.userId)
          .then((res) => {
            this.$message.success(this.$t("common.operate_success"));
            this.fetchData();
          })
          .catch((e) => {
            this.$confirmError(e);
          });
      });
    },
    handleClick(val) {
      const command = val.command;
      const row = val.row;
      if (command === "lock") {
        this.handleLock(row);
      } else if (command === "unlock") {
        this.handleUnlock(row);
      } else if (command === "delete") {
        this.handleDelete(row);
      }
    },
    beforeHandleCommand(command, row) {
      return {
        row: row,
        command: command,
      };
    },

    handleAdd() {
      this.addUserVisible = true;
    },
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.fetchData();
    },
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.fetchData();
    },
  },
};
</script>

<style lang="scss">
.terminal-list {
  .el-table .cell {
    /* height: 30px !important; */
  }
}
</style>

<style lang="scss" scoped>
.query-button {
  margin-left: 30px;
}

.svg-container {
  cursor: pointer;
  margin-top: 6px;
  margin-left: 20px;
  font-size: 24px;
  display: inline-block;
}

.user-list-avatar {
  width: 43.8px;
  height: 43.8px;
  border-radius: 60px;
  overflow: hidden;
  margin: 5px;

  img {
    margin-right: 5px;
    border-radius: 50%;
  }
}

.pagination-wrapper {
  text-align: right;
}
</style>
